# -*- coding: UTF-8 -*-
import collections
import json
import os
from collections.abc import Generator

import yaml


class JsonOps():

    @staticmethod
    def read(file_path):
        # 请求的文件路径不存在则先创建文件夹
        if file_path and not os.path.exists(os.path.dirname(file_path)):
            print(f" ------>> {os.path.dirname(file_path)} <<------  文件夹不存在、已创建文件夹")
            os.mkdir(os.path.dirname(file_path))
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                new_dict = json.load(f, object_pairs_hook=collections.OrderedDict)
            return new_dict
        except FileNotFoundError:
            # 读取文件不存在返回 {} 比返回None更友好
            print(f" ------>> {file_path} <<------  文件不存在,并返回空字典……")
            return {}
        except:
            print(f" ------>> {file_path} <<------  文件读取失败, 返回None……")
            return None

    @staticmethod
    def write(file_path, source):
        dir_name = os.path.dirname(file_path)
        if dir_name and not os.path.exists(dir_name):
            os.mkdir(dir_name)
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(source, f, ensure_ascii=False, indent=2)



class YamlOps():
    @staticmethod
    def read(filename):
        try:
            if not os.path.exists(filename):
                return None
            with open(filename, "rb") as f:
                data_old = yaml.load(f, Loader=yaml.FullLoader)
                return data_old
        except:
            return None


    @staticmethod
    def write(data, filename):
        try:
            dir_name = os.path.dirname(filename)
            if dir_name and not os.path.exists(dir_name):
                os.mkdir(dir_name)

            with open(filename, "w") as f:
                yaml.dump(data, f)
        except:
            return None


class TxtOps():

    @staticmethod
    def read_line(file_path: str) -> Generator:
        '''

        按行读取txt文件 返回生成器对象

        :param file_path: type: string
        :return: type: Generator
        '''
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                data = f.readlines()
                for info in data:
                    if not info or info == "\n":
                        continue
                    yield info.replace("\n", "")

        except:
            return None



if __name__ == '__main__':
    file_path = "../data/pick_point/taobao_doll.txt"
    data = JsonOps.read(file_path)
    print(data)
    # data = TxtOps.read_line(file_path)
    # print(type(data))
    # for info in data:
    #     name, x, y, z= info.split(",")
    #     print(name, x, y, z)